package com.example.sicnuaccountingapp.data.repository

import com.example.sicnuaccountingapp.data.dao.UserDao
import com.example.sicnuaccountingapp.data.entity.User
import com.example.sicnuaccountingapp.utils.DatabaseInitializer
import com.example.sicnuaccountingapp.utils.PreferencesManager
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class UserRepository @Inject constructor(
    private val userDao: UserDao,
    private val preferencesManager: PreferencesManager,
    private val databaseInitializer: DatabaseInitializer
) {
    suspend fun registerUser(username: String, password: String, email: String?, phone: String?): Long {
        val userId = userDao.insertUser(
            User(
                username = username,
                password = password,
                email = email,
                phone = phone
            )
        )
        // 初始化默认分类
        databaseInitializer.initializeDefaultCategories(userId)
        return userId
    }

    suspend fun loginUser(username: String, password: String): User? {
        val user = userDao.getUserByUsername(username)
        return if (user != null && user.password == password) {
            // 保存登录信息
            preferencesManager.saveLoginInfo(user.userId, user.username)
            user
        } else {
            null
        }
    }

    fun getUserById(userId: Long): Flow<User?> {
        return userDao.getUserById(userId)
    }

    suspend fun updateUser(user: User) {
        userDao.update(user)
    }
} 